﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace TheCup.ApiControllers
{

    public class PlayerController : ApiController
    {
        TheCupContext ctx = new TheCupContext();

        public IEnumerable<Player> Get()
        {
            return (from ev in ctx.Players
                     where ev.IsActive
                     select ev).OrderBy(c => c.GivenName).ThenBy(l => l.LastName).ToList<Player>();
        }

        public Player Get(string initials)
        {
            return (from player in ctx.Players
                    where player.Initials == initials
                    select player).FirstOrDefault();
        }

        public Player GetLoggedInPlayer()
        {
            return ctx.Players.FirstOrDefault(p => p.Initials.Equals(User.Identity.Name, StringComparison.InvariantCultureIgnoreCase));
        }

        /// <summary>
        /// TODO add id to Identity, so we don't have to compare on initials
        /// </summary>
        /// <param name="initials"></param>
        /// <returns>true if initials matches the logged in player</returns>
        public bool IsLoggedInPlayer(string initials)
        {
            return GetLoggedInPlayer().Initials.Equals(initials, StringComparison.CurrentCultureIgnoreCase);
        }

        public Player Get(int id)
        {
            return (from player in ctx.Players
                 where player.Id == id
                 select player).FirstOrDefault();
        }

        [Authorize]
        public void Create(Player player)
        {
            ctx.Players.Add(player);
            ctx.SaveChanges();
        }

        // POST api/<controller>
        [Authorize]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        [Authorize]
        public void Put(int id, [FromBody]Player p)
        {
            
        }

        // DELETE api/<controller>/5
        [Authorize]
        public void Delete(int id)
        {
        }

    }

}